unit EUserGroup;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Buttons, ExtCtrls, DB, ZAbstractRODataset, ZAbstractDataset,
  ZDataset, StdCtrls, DBCtrls, Mask, Grids, DBGrids, ComCtrls;

type
  PMyRec = ^Tfield_treeu;

  Tfield_treeu=record
    id:string[20];
    name:string[60];
    fd_type:string[1];
  end;

type
  TfmUserGroup = class(TForm)
    qrUsers: TZQuery;
    dsUsers: TDataSource;
    qrCnt_Id: TZQuery;
    qrLang: TZReadOnlyQuery;
    pnForm: TPanel;
    qrAssAuthorize: TZQuery;
    qrGroup: TZQuery;
    qrUsersNew: TZQuery;
    qrUsersid: TIntegerField;
    qrUsersloginname: TStringField;
    qrUserspwd: TStringField;
    qrUsersname: TStringField;
    qrUsersdept: TStringField;
    qrUsersposit: TStringField;
    qrUsersempid: TStringField;
    qrUsersremark: TStringField;
    qrUsersright_: TStringField;
    qrChk_Usr: TZQuery;
    qrUserspublicadm: TIntegerField;
    Panel2: TPanel;
    dgDetail: TDBGrid;
    Panel3: TPanel;
    GroupBox1: TGroupBox;
    lblCode: TLabel;
    lblLogin: TLabel;
    lblName: TLabel;
    lblEmp: TLabel;
    lblRem: TLabel;
    sbDocno: TSpeedButton;
    edID: TDBEdit;
    edLoginname: TDBEdit;
    edName: TDBEdit;
    DBEdit13: TDBEdit;
    DBEdit14: TDBEdit;
    btSetPwd: TButton;
    DBEdit3: TDBEdit;
    chkAdmin: TDBCheckBox;
    DBCheckBox1: TDBCheckBox;
    Panel1: TPanel;
    sbFirst: TSpeedButton;
    sbPrior: TSpeedButton;
    sbNext: TSpeedButton;
    sbLast: TSpeedButton;
    sbInsert: TSpeedButton;
    sbDelete: TSpeedButton;
    sbEdit: TSpeedButton;
    sbPost: TSpeedButton;
    sbCancel: TSpeedButton;
    sbExit: TSpeedButton;
    procedure FormActivate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure dsUsersDataChange(Sender: TObject; Field: TField);
    procedure sbDocnoClick(Sender: TObject);
    procedure btSetPwdClick(Sender: TObject);
    procedure qrUsersBeforePost(DataSet: TDataSet);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure edLoginnameEnter(Sender: TObject);
    procedure edLoginnameExit(Sender: TObject);
    procedure sbFirstClick(Sender: TObject);
    procedure sbPriorClick(Sender: TObject);
    procedure sbNextClick(Sender: TObject);
    procedure sbLastClick(Sender: TObject);
    procedure sbInsertClick(Sender: TObject);
    procedure sbDeleteClick(Sender: TObject);
    procedure sbEditClick(Sender: TObject);
    procedure sbPostClick(Sender: TObject);
    procedure sbCancelClick(Sender: TObject);
    procedure sbExitClick(Sender: TObject);
    procedure qrUserRightsCalcFields(DataSet: TDataSet);
    procedure gdAuthorizeDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure gdAuthorizeCellClick(Column: TColumn);
    procedure TreeViewCollapsed(Sender: TObject; Node: TTreeNode);
    procedure TreeViewExpanded(Sender: TObject; Node: TTreeNode);
    procedure FormShow(Sender: TObject);
    procedure btRefreshClick(Sender: TObject);
    procedure sbAddGrpClick(Sender: TObject);
    procedure sbDelGrpClick(Sender: TObject);
    procedure sbEditGrpClick(Sender: TObject);
    procedure qrUsersNewRecord(DataSet: TDataSet);
  private
    { Private declarations }
    procedure DataChanged;
    procedure EditingChanged;
    procedure changcaption;

    procedure add2treeview;
    function add2root(Node: TTreeNode; const id_,name_,fd_type_: string): TTreeNode;
  public
    { Public declarations }
    procedure WndProc(var Message: TMessage); override;
  end;

var
  fmUserGroup: TfmUserGroup;

implementation
uses Emain,dmIdocqment,Utility, EPassword,uEncrypt, EGroup, ELkGroup;

{$R *.dfm}

procedure TfmUserGroup.FormActivate(Sender: TObject);
begin
  fmMain.FindButtonQuick(TForm(sender).Handle);

  fmMain.pnAppBar.Parent := TForm(Sender);
  fmMain.pnAppTitle.Parent := TForm(Sender);

  TForm(Sender).Left:=fmMain.Left;
  TForm(Sender).Top:=fmMain.Top;
  TForm(Sender).Width :=fmMain.Width;
  TForm(Sender).Height:=fmMain.Height;
end;

procedure TfmUserGroup.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  fmMain.delete2sbwin(TForm(sender).Handle);
end;

procedure TfmUserGroup.dsUsersDataChange(Sender: TObject;
  Field: TField);
begin
  DataChanged;
  EditingChanged;

  {with qrUserRights do
  begin
    if active then Refresh;
  end;}
end;

procedure TfmUserGroup.DataChanged;
var
  UpEnable, DnEnable,state_ds: Boolean;
begin
  state_ds:=qrUsers.state in [dsInsert,dsEdit];
  UpEnable := Enabled and qrUsers.Active and not qrUsers.BOF;
  DnEnable := Enabled and qrUsers.Active and not qrUsers.EOF;
  sbFirst.Enabled := UpEnable and not state_ds;
  sbPrior.Enabled := UpEnable and not state_ds;
  sbNext.Enabled := DnEnable and not state_ds;
  sbLast.Enabled := DnEnable and not state_ds;
  sbDelete.Enabled := Enabled and qrUsers.Active and
    qrUsers.CanModify and not state_ds and
    not (qrUsers.BOF and qrUsers.EOF);
end;

procedure TfmUserGroup.EditingChanged;
var
  CanModify,modival: Boolean;
begin
  CanModify := Enabled and qrUsers.Active and qrUsers.CanModify;
  modival:=qrUsers.state in [dsInsert,dsEdit];
  sbInsert.Enabled := CanModify and not modival;
  sbEdit.Enabled := CanModify and not modival;
  sbPost.Enabled := CanModify and modival;
  sbCancel.Enabled := CanModify and modival;

  sbExit.Enabled:=sbInsert.Enabled;

  DataChanged;
end;

procedure TfmUserGroup.sbDocnoClick(Sender: TObject);
var
  i:integer;
begin
  if qrUsers.state =dsInsert then
  begin
    qrCnt_Id.close;
    qrCnt_Id.sql.clear;
    qrCnt_Id.sql.add('select max(id) max_id from users ');
    qrCnt_Id.open;
    try
      if qrCnt_Id.isempty then i:=1 else i:=qrCnt_Id.fieldbyname('max_id').asinteger +1;
    except
      i:=1;
    end;

    qrUsers.fieldbyname('id').asinteger:=i;
    //edID.setfocus;
  end;
end;

procedure TfmUserGroup.btSetPwdClick(Sender: TObject);
var fm:TfmPassword;
begin
  if qrAssAuthorize.Locate('rights_code','C005',[]) then
  begin
    check_authorize('edit user');
  end;

  fm:=TfmPassword.create(self);
  try
    if fm.showmodal=mrOK then
    begin
      qrUsers.edit;
      qrUsers.fieldbyname('pwd').asstring:=Encrypt(trim(fm.edPwd.text),my_key);
    end;
  finally
    edName.setfocus;
    fm.free;
    fm:=nil;
  end;
end;

procedure TfmUserGroup.qrUsersBeforePost(DataSet: TDataSet);
begin
  sbDocno.Click;
end;

procedure TfmUserGroup.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key=VK_Up then SelectNext(ActiveControl,false,true);
  if Key=VK_Down then SelectNext(ActiveControl,true,true);
end;

procedure TfmUserGroup.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key=#13 then SelectNext(ActiveControl,true,true);
end;

procedure TfmUserGroup.edLoginnameEnter(Sender: TObject);
begin
  SetBackColor(Sender,true);
end;

procedure TfmUserGroup.edLoginnameExit(Sender: TObject);
begin
  SetBackColor(Sender,false);
end;

procedure TfmUserGroup.sbFirstClick(Sender: TObject);
begin
  qrUsers.First;
end;

procedure TfmUserGroup.sbPriorClick(Sender: TObject);
begin
  qrUsers.Prior;
end;

procedure TfmUserGroup.sbNextClick(Sender: TObject);
begin
  qrUsers.Next;
end;

procedure TfmUserGroup.sbLastClick(Sender: TObject);
begin
  qrUsers.Last;
end;

procedure TfmUserGroup.sbInsertClick(Sender: TObject);
begin
  if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('append user');
  end;

  qrUsers.Append;
end;

procedure TfmUserGroup.sbDeleteClick(Sender: TObject);
begin
  if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('delete user');
  end;

  if MessageDlg('Do you want to delete record?. [Yes/No]',
    mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  begin
    qrUsers.Delete;
    qrUsers.ApplyUpdates;
  end;
end;

procedure TfmUserGroup.sbEditClick(Sender: TObject);
begin
  if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('edit user');
  end;

  qrUsers.Edit;
end;

procedure TfmUserGroup.sbPostClick(Sender: TObject);
begin
  if qrUsers.state=dsInsert then
  begin
    if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
    begin
      check_authorize('append user');
    end;
  end ;
  if qrUsers.state=dsEdit then
  begin
    if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
    begin
      check_authorize('edit user');
    end;
  end ;

  qrUsers.post;
  qrUsers.ApplyUpdates;
end;

procedure TfmUserGroup.sbCancelClick(Sender: TObject);
begin
  qrUsers.CancelUpdates;
end;

procedure TfmUserGroup.sbExitClick(Sender: TObject);
begin
  close;
end;

procedure TfmUserGroup.WndProc(var Message: TMessage);
begin
  case Message.Msg Of
    QEventType_CMSetLang : changcaption;
  else
    inherited;
  end;
end;

procedure TfmUserGroup.changcaption;
begin
  with qrLang do
  begin
    close;
    parambyname('lang').asstring:=dm.languagedef;
    open;
    lblCode.caption:=Get2Caption(qrLang,'C001','Code');
    lblLogin.caption:=Get2Caption(qrLang,'C002','Login Name');
    lblName.caption:=Get2Caption(qrLang,'C003','Name');
    btSetPwd.caption:=Get2Caption(qrLang,'C004','Set Password');
    lblEmp.caption:=Get2Caption(qrLang,'C005','Emp. ID');
    lblRem.caption:=Get2Caption(qrLang,'C006','Remark');
    chkAdmin.caption:=Get2Caption(qrLang,'C008','Administrator');
  end;
  with dgDetail do
  begin
    columns[0].Title.caption:=lblCode.caption;
    columns[1].Title.caption:=lblLogin.caption;
    columns[2].Title.caption:=lblName.caption;
    //columns[3].Title.caption:=lblRem.caption;
  end;

  with dm.qrLang do
  begin
    close;
    parambyname('lang').asstring:=dm.languagedef;
    open;
  end;
  sbFirst.hint:=Get2Caption(dm.qrLang,'C001','First Record');
  sbPrior.hint:=Get2Caption(dm.qrLang,'C002','Prior Record');
  sbNext.hint:=Get2Caption(dm.qrLang,'C003','Next Record');
  sbLast.hint:=Get2Caption(dm.qrLang,'C004','Last Record');
  sbInsert.hint:=Get2Caption(dm.qrLang,'C005','Append Record');
  sbDelete.hint:=Get2Caption(dm.qrLang,'C006','Delete Record');
  sbEdit.hint:=Get2Caption(dm.qrLang,'C007','Edit Record');
  sbPost.hint:=Get2Caption(dm.qrLang,'C008','Save Record');
  sbCancel.hint:=Get2Caption(dm.qrLang,'C009','Cancel Record');
  sbExit.hint:=Get2Caption(dm.qrLang,'C010','Close Form');

  //sbAddGrp.hint:=sbInsert.hint;
  //sbDelGrp.hint:=sbDelete.hint;
  //sbEditGrp.hint:=sbEdit.hint;
end;

procedure TfmUserGroup.qrUserRightsCalcFields(DataSet: TDataSet);
begin
  {if dataset.active then
  with qrAuthorize do
  begin
    if active then close;
    params[0].asstring:=qrUsers.fieldbyname('loginname').asstring;
    params[1].asstring:=dataset.fieldbyname('Rights_Code').asstring;
    params.parambyname('rightsgrp').asstring:=dataset.fieldbyname('rightsgrp').asstring;
    open;
    qrUserRights.fieldbyname('access').asinteger:= Fields[0].AsInteger;
  end;}
end;

procedure TfmUserGroup.gdAuthorizeDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
begin
  (*if Column.Index = 2 then
  begin
    if qrUserRights.fieldbyname('access').asinteger=0 then
    begin
      with gdAuthorize do
      begin
        if gdSelected in state then
          Canvas.Pen.Color := clWhite
        else
          Canvas.Pen.Color := clGreen;

        Canvas.Rectangle(Rect.Left+13,Rect.Top+4,Rect.Right -15,Rect.Bottom-4);
        Canvas.MoveTo(Rect.Left+13,Rect.Top+4);
        Canvas.LineTo(Rect.Right -16,Rect.Bottom-5);
        Canvas.MoveTo(Rect.Right-16,Rect.Top+4);
        Canvas.LineTo(Rect.Left+13,Rect.Bottom-5);
      end;
    end else
    begin
      with gdAuthorize do
      begin
        Canvas.Pen.Color := clRed;
        Canvas.Rectangle(Rect.Left+13,Rect.Top+4,Rect.Right -15,Rect.Bottom-4);
      end;
    end;
  end;*)
end;

procedure TfmUserGroup.gdAuthorizeCellClick(Column: TColumn);
var bAccess:integer;
begin
  (*if column.index = 2 then
  begin
    //--check permission users ;
    if qrAssAuthorize.Locate('rights_code','C006',[]) then
    begin
      check_authorize('assign authorize');
    end;

    if not(qrUserRights.state in [dsInsert,dsEdit])then qrUserRights.edit;
    bAccess:=qrUserRights.fieldbyname('access').asinteger;
    if bAccess=1 then
    begin
      with qrDel_Auth do
      begin
        if active then close;
        params[0].asstring:=qrUsers.fieldbyname('loginname').asstring;
        params[1].asstring:=qrUserRights.fieldbyname('Rights_Code').asstring;
        parambyname('rightsgrp').asstring:=qrUserRights.fieldbyname('rightsgrp').asstring;
        ExecSQL;
        qrUserRights.fieldbyname('access').asinteger:=0;
      end;
    end else
    begin
      if Trim(qrUsers.FieldByName('loginname').AsString) = '' then
      begin
        qrUserRights.Cancel;
        MessageDlg('Invalid login name',mtError,[mbOk],0);
        edLoginname.SetFocus;
        SysUtils.Abort;
      end else
      begin
        with qrApp_Auth do
        begin
          try
            if active then close;
            params[0].asstring:=qrUsers.FieldByName('loginname').AsString;
            params[1].asstring:=qrUserRights.FieldByName('Rights_Code').AsString;
            params[2].asstring:=qrUserRights.FieldByName('rightsgrp').AsString;
            ExecSQL;
          except on e:exception do
            sm(e.message);
          end;
        end;
      end;
      qrUserRights.fieldbyname('access').asinteger:=1;
    end;
    qrUserRights.post;
  end;*)
end;

procedure TfmUserGroup.TreeViewCollapsed(Sender: TObject;
  Node: TTreeNode);
begin
  //TreeView.Repaint;
end;

procedure TfmUserGroup.TreeViewExpanded(Sender: TObject; Node: TTreeNode);
begin
  //TreeView.Repaint;
end;

procedure TfmUserGroup.add2treeview;
var
  Node,Node0,Nodenil:TTreeNode;
begin
  //TreeView.Items.clear;
  //TreeView.AutoExpand:=true;
  Nodenil:=add2root(nil,'0',dm.cnDB.Database,'N');

  //--add node doc cabinet;
  //TreeView.Items.BeginUpdate;
  qrGroup.close;
  qrGroup.open;
  if not qrGroup.isempty then
  begin
    qrGroup.first;
    while not qrGroup.eof do
    begin
      Node0:=add2root(Nodenil,
        qrGroup.fieldbyname('id').asstring,
        qrGroup.fieldbyname('name').asstring,'G');

      qrUsersNew.close;
      qrUsersNew.parambyname('dept').asstring:=qrGroup.fieldbyname('id').asstring;
      qrUsersNew.open;
      if not qrUsersNew.isempty then
      begin
        qrUsersNew.first;
        while not qrUsersNew.eof do
        begin
          Node:=add2root(Node0,
            qrUsersNew.fieldbyname('id').asstring,
            qrUsersNew.fieldbyname('loginname').asstring,'U');

          qrUsersNew.next;
        end;
      end;
      qrGroup.next;
    end;
  end;
  //TreeView.Items.EndUpdate;
end;

function TfmUserGroup.add2root(Node: TTreeNode; const id_,name_,fd_type_: string): TTreeNode;
var
  MyRecPtr: PMyRec;
begin
  (*with TreeView.Items do
  begin
    //Clear; { remove any existing nodes }
    //MyTreeNode1 := Add(nil, dm.cnIdoc.Database); { Add a root node }
    New(MyRecPtr);
    MyRecPtr^.id:=id_ ;
    MyRecPtr^.name:=name_;
    MyRecPtr^.fd_type:=fd_type_;

    if Node = nil then
      result:=AddObject(Node,name_ , MyRecPtr)
    else result:=AddChildObject(Node,name_,MyRecPtr);

    TreeView.FullExpand;
  end;
  *)
end;

procedure TfmUserGroup.FormShow(Sender: TObject);
begin
  //add2treeview;
  fmMain.add2sbwin(TForm(sender).Handle,TForm(sender).caption,TForm(sender).name);

  changcaption;
  qrUsers.open;
  //qrGroup.open;
  //qrUserRights.open;

  dm.qrChk_Right.close;
  dm.qrChk_Right.parambyname('loginname').asstring:=dm.users;
  dm.qrChk_Right.open;

  with qrAssAuthorize do
  begin
    close;
    parambyname('loginname').asstring:=dm.users;
    parambyname('rightsgrp').asstring:='USR';
    open;
  end;  
end;

procedure TfmUserGroup.btRefreshClick(Sender: TObject);
var Node:TTreeNode;
  lk:string;
begin
  //lk:=PMyRec(TreeView.Selected.Data)^.link_id; //qrDoc.fieldbyname('link').asstring;
  add2treeview;
  (*FChange_Tree:=false;
  Node:=GetNodeByText(TreeView,lk,true);
  if Node<>nil then
  begin
    if TreeView.CanFocus then TreeView.SetFocus;
    Node.Selected:=true;
    //showtreesearchall;
    //PageControl1.ActivePageIndex:=0;
  end;
  FChange_Tree:=true;*)
end;

procedure TfmUserGroup.sbAddGrpClick(Sender: TObject);
var fm:TfmGroup;
  mx_id:Longint;
  Node:TTreeNode;
  x,y:integer;
begin
  (*if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('create groups');
  end;

  fm:=TfmGroup.create(self);
  try
    x:=TreeView.ClientOrigin.X;
    y:=TreeView.ClientOrigin.Y;
    fm.Left:=x - left -5;
    fm.top:=y - Top -15;

    if fm.showmodal=mrOK then
    begin
      if fm.edName.text <> '' then
      begin
        qrMax_Group.close;
        qrMax_Group.open;
        mx_id:=1;
        if not qrMax_Group.isempty then
        begin
          try
            mx_id:=qrMax_Group.fieldbyname('max_id').asinteger + 1;
          except
            mx_id:=1;
          end;
        end;

        Node:=add2root(TreeView.TopItem,intTostr(mx_id),fm.edName.text,'G');

        qrAdd_Depart.parambyname('id').asstring:=intTostr(mx_id);
        qrAdd_Depart.parambyname('name').asstring:=fm.edName.text;
        qrAdd_Depart.ExecSQL;
      end;
    end;
  finally
    fm.free;
    fm:=nil;
  end;
  *)
end;

procedure TfmUserGroup.sbDelGrpClick(Sender: TObject);
begin
  (*if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('delete groups');
  end;

  if PMyRec(TreeView.Selected.Data)^.fd_type='G' then
  begin
    if MessageDlg('Do you want to delete record?. [Yes/No]',
      mtConfirmation, [mbYes, mbNo], 0) = mrYes then
    begin
      qrChk_Usr.close;
      qrChk_Usr.parambyname('dept').asstring:=PMyRec(TreeView.Selected.Data)^.id;
      qrChk_Usr.open;

      if qrChk_Usr.isempty then
      begin
        qrDel_Depart.parambyname('id').asstring:=PMyRec(TreeView.Selected.Data)^.id;
        qrDel_Depart.ExecSql;

        TreeView.Items.Delete(TreeView.Selected);
      end else
      begin
        btRefresh.click;
        showmessage('Can not delete this group is user already exist!');
      end;
    end;
  end;
  *)
end;

procedure TfmUserGroup.sbEditGrpClick(Sender: TObject);
var fm:TfmGroup;
  x,y :integer;
begin
  (*if dm.qrChk_Right.fieldbyname('posit').asstring<>'A' then
  begin
    check_authorize('edit groups');
  end;

  if PMyRec(TreeView.Selected.Data)^.fd_type='G'then
  begin
    fm:=TfmGroup.create(self);
    x:=TreeView.ClientOrigin.X;
    y:=TreeView.ClientOrigin.Y;
    fm.Left:=x - left -5;
    fm.top:=y - Top -15;
    try
      fm.edName.text:=TreeView.Selected.Text;
      if fm.showmodal=mrOK then
      begin
        TreeView.Selected.Text:=fm.edName.text;
        qrUpdDepart.parambyname('name').asstring:=fm.edName.text;
        qrUpdDepart.parambyname('id').asstring:=PMyRec(TreeView.Selected.Data)^.id;
        qrUpdDepart.Execsql;
      end;
    finally
      fm.free;
      fm:=nil;
    end;
  end;
  *)
end;

procedure TfmUserGroup.qrUsersNewRecord(DataSet: TDataSet);
begin
  DataSet.fieldbyname('posit').asstring:='B';
end;

end.
